package com.gowants.pems.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.model.SysDict;
import com.gowants.pems.service.SysDictService;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.JSONList;
import com.gowants.pems.util.JSONMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/sysDict")
public class SysDictController extends BaseController
{
    @Autowired
    private SysDictService ScmsDictService;
    
    /**
     * <用户等级列表查看>
     * @param page
     * @param limit
     * @param reqData
     * @param req
     * @return
     * @remake create by TPH 2020年4月8日 上午10:50:22
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "字典列表查看", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
            @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
            @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
            HttpServletRequest req) 
    {
        if (!isPower("/sysDict/getList.do")) 
        {
            return doResponse(req, "TSMS_0000228");
        }
        JSONMap resultMap = new JSONMap();
        SysDict record = new SysDict();
        if (!"".equals(reqData)) 
        {
            JSONList jsonCondition = getCondition(reqData);
            // 封装时间类查询条件
            buildDateCondition(jsonCondition, record);

            for (Object cond : jsonCondition) {
                this.buildCondition(cond, record);
            }
        }
        // 设置分页查询信息
        PageHelper.startPage(page, limit);
        List<SysDict> list = ScmsDictService.select(record);
        PageInfo<SysDict> pageInfo = new PageInfo<SysDict>(list);
        // 赋值方法
        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

        return doResponse(req, "", resultMap);
    }
    /**
     * <用户等级列表查看>
     * @param page
     * @param limit
     * @param reqData
     * @param req
     * @return
     * @remake 
     */
    @RequestMapping(value = "/getListNew", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "字典通用列表查看", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getListNew(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
            @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
            @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
            HttpServletRequest req) 
    {
        if (!isPower("/sysDict/getListNew.do")) 
        {
            return doResponse(req, "TSMS_0000228");
        }
        JSONMap resultMap = new JSONMap();
        SysDict record = new SysDict();
        if (!"".equals(reqData)) 
        {
            JSONList jsonCondition = getCondition(reqData);
            // 封装时间类查询条件
            buildDateCondition(jsonCondition, record);

            for (Object cond : jsonCondition) {
                this.buildCondition(cond, record);
            }
        }
        // 设置分页查询信息
        PageHelper.startPage(page, limit);
        List<SysDict> list = ScmsDictService.selectNew(record);
        PageInfo<SysDict> pageInfo = new PageInfo<SysDict>(list);
        // 赋值方法
        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

        return doResponse(req, "", resultMap);
    }
    /**
     * <保存>
     * @param request
     * @param req
     * @return
     * @remake create by TPH 2020年4月8日 上午11:22:22
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "字典保存", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap save(String request, HttpServletRequest req) 
    {
        if (!isPower("/sysDict/save.do")) 
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000036";
        try
        {
            SysDict record = getRequestBody(request, SysDict.class);
            //校验 groupId+dictId是否重复
            int count = ScmsDictService.saveCheck(record);
            if(count > 0) 
            {
                return doResponse(req, "TSMS_0000246", null);
            }
            int exeNum = ScmsDictService.save(record);
            if(exeNum > 0) 
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        
        return doResponse(req, code, null);
    }
    
    /**
     * <删除>
     * @param request
     * @param req
     * @return
     * @remake create by TPH 2020年4月8日 上午11:40:45
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "字典删除", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap delete(String request, HttpServletRequest req) 
    {
        if (!isPower("/sysDict/delete.do")) 
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000048";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            int exeNum = ScmsDictService.delete(id);
            if(exeNum > 0) 
            {
                code = "TSMS_0000050";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        return doResponse(req, code, null);
    }
    
    /**
     * <修改>
     * @param request
     * @param req
     * @return
     * @remake create by TPH 2020年4月8日 上午11:16:31
     */
    @RequestMapping(value = "/update")
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "字典修改", opType = OperType.execute, importance = Importance.important)
    public JSONMap update(String request, HttpServletRequest req) 
    {
        if (!isPower("/sysDict/update.do")) 
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000053";
        try 
        {   
            SysDict record = getRequestBody(request, SysDict.class);
            //校验groupId和dictId重复
            int count = ScmsDictService.updateCheck(record);
            if(count > 0)
            {
                return doResponse(req, "TSMS_0000246", null);
            }
            int exeNum = ScmsDictService.update(record);
            if(exeNum > 0) 
            {
                code = "TSMS_0000002";
            }
               
        } 
        catch (Exception e) 
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    } 
    
    private void buildDateCondition(JSONList jsonCondition, SysDict record) 
    {
        Date startTime = null;
        Date endTime = null;

        for (Object cond : jsonCondition) {
            JSONMap condition = JSONMap.parseJSONMap(cond.toString());
            String field = condition.getString("field");

            if (field.equals("startTime")) {
                startTime = DateUtil.dateFormat(condition.getString("keyword"));
                continue;
            }

            if (field.equals("endTime")) {
                endTime = DateUtil.dateFormat(condition.getString("keyword"));
                continue;
            }
        }

        if (null != startTime && null == endTime) {
            endTime = DateUtil.getMaxTime(new Date());
            record.setStartTime(startTime);
            record.setEndTime(endTime);
        }

        if (null != startTime && null != endTime) {
            record.setStartTime(startTime);
            record.setEndTime(endTime);
        }
    }
    
    private void buildCondition(Object cond, SysDict record) 
    {
        JSONMap condition = JSONMap.parseJSONMap(cond.toString());

        String field = condition.getString("field");
        String keyword = condition.getString("keyword");

        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword)) 
        {
            switch (field) 
            {
                case "id":
                    record.setId(keyword);
                    break;
                case "dictId":
                    record.setDictId(Integer.parseInt(keyword));
                    break;
                case "dictName":
                    record.setDictName(keyword);
                    break;
                case "groupId":
                    record.setGroupId(keyword);
                    break;
            }
        }
    }
    
    /**
	 * 公共方法
	 * 
	 * @param request={"dictId":"","groupId":""}
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/dictPublic")
    @AccessLimit(seconds = 1, maxCount = 10,needLogin=true) //1秒内 允许请求3次
	public JSONMap dictPublics(String request, HttpServletRequest req) {
		SysDict ScmsDict = new SysDict();
		if (StringUtils.isNotEmpty(request)) {
			ScmsDict = getRequestBody(request, SysDict.class);
		}
		List<SysDict> userList = ScmsDictService.selectList(ScmsDict);
		return doResponse(req, "", userList);

	}
    
}
